<?php
//设备管理
namespace app\ausagent\controller;
use app\ausagent\controller\Common;
use think\Request;
use think\Loader;
use think\Db;
use think\Cache;
use think\Session;
use think\Cookie;
use think\Controller;
use think\Config;
use Godok\Org\Auth;
use mlsmt\Cabinet\Send;
use think\Validate;

class Equipment extends Common{
    public function index($sid=""){
        $pages = 20;
        $sid =  Request::instance()->get('sid','','number_int');

        $pageParam    = ['query' =>[]];//按分页条件查找
        if((!empty(input('name'))) or (!empty(input('area')))){
            $where = 'a.is_delete=1 and a.oid = '.session('oid');
            if($sid!=''){
                $where .= ' AND a.sid = '.$sid;
                $pageParam['query']['sid'] = $sid;
            }
            //判断是否有表单提交的数据
            if(!empty(input('name'))){

                $where .= ' AND b.name LIKE '."'%".input('name')."%' ";
                $pageParam['query']['b.name'] = input('name');
            }

            if(!empty(input('area'))){
                $where .= ' AND b.area LIKE '."'%".input('area')."%' ";
                $pageParam['query']['b.area'] = input('area');
            }


            $s = 'seller';//商户表
            $list = DB::name('charecabinet')
                ->alias('a')
                ->join("$s b",'a.oid = b.oid and a.sid = b.id')
                ->field('a.id,a.cabinet_id,a.model,a.mode,a.status,b.name,b.area,b.addr')
                ->where($where)
                ->order('a.create_time desc')
                ->paginate($pages,false, $pageParam);
            //var_dump($list);die;
        }else{
            $where = 'is_delete=1 and oid = '.session('oid');
            if($sid!=''){
                $where .= ' AND sid = '.$sid;
                $pageParam['query']['sid'] = $sid;
            }
            if(!empty(input('cabinet_id'))){
                $where .= ' AND cabinet_id LIKE '."'%".input('cabinet_id')."%' ";
                $pageParam['query']['cabinet_id'] = input('cabinet_id');
            }
            $list = Db::name('charecabinet')
                ->where($where)
                ->order('create_time desc')
                ->paginate($pages,false, $pageParam);
            $data2 = $list->all();
            foreach ($data2 as $k => $v) {
                $ret = Db::name('seller')
                    ->where('id',$v['sid'])
                    ->where('is_delete',1)
                    ->field('name,area,addr')
                    ->find();
                if($ret){
                    $v['name'] = $ret['name'];
                    $v['area'] = $ret['area'];
                    $v['addr'] = $ret['addr'];
                    $list[$k] = $v;
                }else{
                    $v['name'] = '';
                    $v['area'] = '';
                    $v['addr'] = '';
                    $list[$k] = $v;
                }
            }
        }
        $data = $list->all();
        $time = time();
        foreach ($data  as $k=>$v) {
            $data2 = Cache::store('redis')->get($v['cabinet_id']);
            isset($data2['heartbeattime'])?$v['heartbeattime']=$data2['heartbeattime']:$v['heartbeattime']='';
            isset($data2['clientip'])?$v['clientip']=$data2['clientip']:$v['clientip']='';
            $v['times'] = $time - $v['heartbeattime'];
            $list[$k] = $v;
        }
        //var_dump($list);die;
        $this->assign('list',$list);
        return $this->fetch();
    }
    public function add(){

        if ( Request::instance()->isPost()) {
            $data = input('post.');
            $data['oid'] = session('oid');
            $data['create_user'] = session('id');
            $data['create_time'] = time();
            $data['is_delete'] = 1;
            $validate = \think\Loader::validate('Charecabinet');
            if(!$validate->scene('add')->check($data)){
                $this->error(lang($validate->getError()));
            }
            if(Db::name('charecabinet')->insert($data)){
                $oid = session('oid');$m = 'ausagent'; $c = 'Equipment'; $action="add"; $uid=session('id'); $querystring = '添加设备信息';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                return  ['code'=>0, 'msg'=>lang('添加机柜信息成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('添加机柜信息失败！')];
            }
            //return;
            //var_dump($data); die;

        }else{
            $where = 'is_delete=1 and oid = '.session('oid');
            $list= Db::name( 'seller')
                ->where($where)
                ->order('create_time desc')
                ->select();
            $this->assign('list',$list);
            return $this->fetch();
        }

    }

    public function details(){
        $id = Request::instance()->get('id','','number_int');
        //echo $id; die;
        $data = DB::name('charecabinet')
            ->where('id',$id)
            ->find();
        //cabinet_id	
        $cabinet_id = $data['cabinet_id'];
        $Send = new Send($cabinet_id);
        $stockDetail = $Send->StockDetail();//获取库存明细


        /*$logdata = array(
            'oid' => session('oid'),
            'mode' => 2,
            'operation' => 6,
            'info' => '',
            'resstatus' => $stockDetail['types'],
            'result' => $stockDetail['info'],
            'create_user'  => session('id'),
          );
          isset($stockDetail['hex'])? $logdata['reshex']=$stockDetail['hex']:'';
          $Send->Log($logdata);//记录机柜日志*/

        $data = array(
            'stockDetail'      => $stockDetail,
        );
        //var_dump($stockDetail);die;
        $this->assign('data',$data);
        $this->assign('cabinet_id',$cabinet_id);
        return $this->fetch('../application/publicview/equipment/details.html');
    }

    //以下是充电宝有关的信息
    public function electricize(){
        $pages = 20;
        $where = 'a.is_delete=1 and a.oid = '.session('oid');
        $user = Config::get('auth.table_user');
        $list = DB::name('portablebattery')
            ->alias('a')
            ->join("$user b","a.oid = b.oid and a.create_user = b.id")
            ->field('a.id,a.device_id,a.create_user,a.status,a.create_time,b.username,b.name,b.phone')
            ->where($where)
            ->order('a.create_time desc')
            ->paginate($pages);
//        echo Db::name('portablebattery')->getLastSql();

        $this->assign('list',$list);
        return $this->fetch('../application/publicview/equipment/electricize.html');
    }

    public function record(){
        $pages = 20;
        $where = 'a.is_delete=1 and a.oid = '.session('oid');
        if(!empty(input('deviceid'))){

            $where .= ' AND b.deviceid LIKE '."'%".input('deviceid')."%' ";
            //$pageParam['query']['b.name'] = input('name');
        }
        $a = 'leaseorder';//租借记录表
        $list = DB::name('portablebattery')
            ->alias('a')
            ->join("$a b",'a.oid = b.oid and a.device_id = b.deviceid')
            ->field("ifnull(count(b.deviceid),0) as amount, a.device_id ,a.id")
            ->where($where)
            ->group('a.device_id,a.id')
            ->paginate($pages);
        //var_dump($list);die;   
        //echo Db::name('portablebattery')->getlastsql();   
        $this->assign('list',$list);
        return $this->fetch('../application/publicview/equipment/record.html');
    }

    //生成二维码
    public function createqrcode($id=null)
    {
        ob_clean();
        if($id){
            $oid = session('oid');
            $oid2 = mwencrypt((string)$oid);
            $cid = $id;
            $website = config('qrcodeurl');

            $data = '/Lease?objhxy='.$oid2.'&&cineda='.$cid;
            $url = $website .$data;


            $errorCorrectionLevel = 'L';//容错级别
            $matrixPointSize = intval(18);//生成图片大小
            //生成二维码图片
            Loader::import('qrcode.phpqrcode');
            $object = new \QRcode();

            $object->png($url, 'qrcode.png', $errorCorrectionLevel, $matrixPointSize, 2);

            /*$logo = DB::name('operator')
                ->where('id',$oid)
                ->cache(true)
                ->find();*/
            $QR = 'qrcode.png';//已经生成的原始二维码图 
            $QR = imagecreatefromstring(file_get_contents($QR)); //打开文件
            //如果有logo则将LOGO合并
            /*if ($logo != '') { 

                $logo = $website.$logo['logo']; //连接完整的logo地址
                
                $logo = imagecreatefromstring(file_get_contents($logo)); 
                $QR_width = imagesx($QR);//二维码图片宽度 
                $QR_height = imagesy($QR);//二维码图片高度 
                $logo_width = imagesx($logo);//logo图片宽度 
                $logo_height = imagesy($logo);//logo图片高度 
                $logo_qr_width = $QR_width / 5; 
                $scale = $logo_width/$logo_qr_width; 
                $logo_qr_height = $logo_height/$scale; 
                $from_width = ($QR_width - $logo_qr_width) / 2; 
                //重新组合图片并调整大小 
                imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, 
                $logo_qr_height, $logo_width, $logo_height); 
                
            }*/
            //输出图片 
            Header("Content-type: image/png");
            ImagePng($QR,'qrcode.png');
            $qrcode =  '<img src="/qrcode.png" alt="" width="200px" >';
            echo $qrcode;

        }
    }
    //查询可借可充充电宝数量
    public function totales($cabinet_id=''){
        $cabinet_id = input('param.cabinet_id');
        $Send = new Send($cabinet_id);
        $totals = $Send->StockNum();//获取总库存量
        isset($totals['info'])?$total=$totals['info']:$total='';
        isset($totals['types'])?$type=$totals['types']:$type='';

        $devicenum = Db::name('charecabinet')->where(['cabinet_id' => $cabinet_id, 'is_delete' => 1])->field('cabinet_id, devicenum')->find();

        if($type){
            /*$logdata = array(
                'oid' => 0,
                'mode' => 2,
                'operation' => 'StockNum',
                'info' => '',
                'result' => $totals,
                'create_user'  => session('adminid'),
              );
              isset($totals['hex'])? $logdata['reshex']=$totals['hex']:'';
              $Send->Log($logdata);*///记录机柜日志

            return ['code'=>0, 'msg'=> $total, 'devicenum'=>$devicenum['devicenum']];
        }else{
            return ['code'=>1, 'msg'=>'', 'devicenum'=>$devicenum['devicenum']];
        }

    }
    //更新机柜信息
    public function edit($id=""){

        if ( Request::instance()->isPost() ) {
            $data = input('post.');
            $validate = \think\Loader::validate('Charecabinet');
            if(!$validate->scene('edit')->check($data)){
//                $this->error(lang($validate->getError()));
                return ['code'=>-1050, 'msg'=>lang($validate->getError())];
            }
            if(Db::name( 'charecabinet')->update($data)){
                //$this->redirect('index');
                return ['code'=>0, 'msg'=>lang('修改成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('修改失败！')];
            }
            //return;
        }else{
            $where['id'] = $id;
            $charecabinet = Db::name('charecabinet')->where($where)->find();
            $where2['is_delete'] = 1;
            $where2['oid'] = session('oid');
            $where2['status'] = 1;
            $list = Db::name('seller')
                ->field('id,name')
                ->where($where2)
                ->select();
            $this->assign('list',$list);
            $this->assign('v',$charecabinet);
            $oid = session('oid');$m = 'ausagent'; $c = 'Equipment'; $action="edit"; $uid=session('id'); $querystring = '更新'.$charecabinet['cabinet_id'].'设备信息';
            $ip = get_ip();$os = get_os();
            set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
            return $this->fetch();

        }

    }
    //删除机柜信息
    public function delete($id=""){
        $id =  Request::instance()->get('id','','number_int');
        if($id){
            $data['id'] = $id;
            $data['is_delete'] =0;
            if(Db::name( 'charecabinet')->update($data)){
                //$this->redirect('index');
                $oid = session('oid');$m = 'ausagent'; $c = 'Equipment'; $action="delete"; $uid=session('id'); $querystring = '删除'.$id.'机柜信息';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                return ['code'=>0, 'msg'=>lang('删除成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('删除失败！')];
            }

        }
    }

    //查看机柜配置信息
    /*public function configure($cabinet_id=''){
    	$cabinet_id = input('param.cabinet_id');
    	$Send = new Send($cabinet_id);
    	if(!empty($cabinet_id)){
    		$config = $Send->GetConfigure();//获取配置文件//新机柜无此功能
			if($config['types']){
				$logdata = array(
			        'oid' => session('oid'),
			        'mode' => 2,
			        'operation' => 7,
			        'info' => '',
			        'resstatus' => $config['types'],
			        'result' => $config['info'],
			        'create_user'  => session('id'),
			  	);
	  			isset($config['hex'])? $logdata['reshex']=$config['hex']:'';
			  	$Send->Log($logdata);//记录机柜日志
				$configures = $config['info'];
				
				$this->assign('v',$configures);
			}else{
				$data = '暂无设备配置信息';
				$this->assign('view',$data);
			}	
    	}
		
		//var_dump($config);die;
		
		return $this->fetch('../application/publicview/equipment/configure.html');
    }*/

    //查看版本信息
    public function version(){
        $cabinet_id = input('param.cabinet_id');
        $Send = new Send($cabinet_id);
        if(!empty($cabinet_id)){
            $version = $Send->Version();//获取版本号
            //var_dump($version);die;
            if($version['types']){
                /*$logdata = array(
                    'oid' => session('oid'),
                    'mode' => 2,
                    'operation' => 8,
                    'info' => '',
                    'resstatus' => $version['types'],
                    'result' => $version['info'],
                    'create_user'  => session('id'),
                  );
                  isset($version['hex'])? $logdata['reshex']=$version['hex']:'';
                  $Send->Log($logdata);//记录机柜日志*/
                $versions = $version['info'];

                $this->assign('v',$versions);
            }else{
                $data = '暂无设备版本信息';
                $this->assign('view',$data);
            }
        }

        return $this->fetch('../application/publicview/equipment/version.html');
    }
    //重启设备
    public function restart(){
        $id = input('param.cabinet_id');
        if(!empty($id)){
            $this->assign('id',$id);
            return $this->fetch('../application/publicview/equipment/restart.html');
        }
        if(input('id')){
            $id = input('param.id');
            //var_dump($id);die;
            $Send = new Send($id);
            $result = $Send->Restart();
            if($result['types']==1){
                $logdata = array(
                    'oid' => session('oid'),
                    'mode' => 2,
                    'operation' => 5,
                    'info' => '',
                    'resstatus' => $result['types'],
                    'result' => $result['info'],
                    'create_user'  => session('id'),
                );
                isset($version['hex'])? $result['hex']=$result['hex']:'';
                $Send->Log($logdata);//记录机柜日志
                $oid = session('oid');$m = 'ausagent'; $c = 'Equipment'; $action="restart"; $uid=session('id'); $querystring = '重启'.$id.'机柜';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                return ['code'=>0, 'msg'=>lang('重启成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('重启失败！')];
            }

        }




    }

    public function updateconf(){

        if ( Request::instance()->isPost() ) {
            //var_dump(input('post.'));die;
            $data = input('post.');
            //验证
            $validate = new Validate();
            $validate -> rule([
                ['cabinet_id','require','缺少参数机柜id'],
                ['servicer','require','缺少参数服务器地址'],
                ['port','require','缺少参数服务器端口'],
                ['heartbeat','require','缺少参数心跳'],
            ]);
            $result = $validate->check($data);
            if(!$result){
                return ['code'=>-1051, 'msg'=>$validate->getError()];
            }

            $cabinet_id = $data['cabinet_id'];
            $addr = $data['servicer'];
            $port = $data['port'];
            $heartbeat = $data['heartbeat'];
            $Send = new Send($cabinet_id);
            $setconfig = $Send->UpdateStatus($addr,$port,$heartbeat);
            //var_dump($setconfig);die;
            if($setconfig['types']) {
                /*$logdata = array(
                    'oid' => session('oid'),
                    'mode' => 2,
                    'operation' => 3,
                    'info' =>   json_encode(array(
                        'addr' =>$addr, 
                        'port' =>$port,
                        'heartbeat' =>$heartbeat , 
                    )),
                    'resstatus' => $setconfig['types'],
                    'result' => $setconfig['info'],
                    'create_user'  => session('id'),
                  );
                  isset($setconfig['hex'])? $result['hex']=$setconfig['hex']:'';
                  $Send->Log($logdata);//记录机柜日志*/
                $oid = session('oid');$m = 'ausagent'; $c = 'Equipment'; $action="updateconf"; $uid=session('id'); $querystring = '更新'.$cabinet_id.'机柜配置信息';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                return ['code'=>0, 'msg'=>lang('修改成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('删除失败！')];
            }


        }else{
            $cabinet_id = input('param.cabinet_id');
            /*$Send = new Send($cabinet_id);
            $config = $Send->GetConfigure();*/
            if(!empty($cabinet_id)){
                /*if($config){
                    $logdata = array(
                        'oid' => session('oid'),
                        'mode' => 2,
                        'operation' => 7,
                        'info' => '',
                        'resstatus' => $config['types'],
                        'result' => $config['info'],
                        'create_user'  => session('id'),
                      );
                      isset($config['hex'])? $result['hex']=$config['hex']:'';
                      $Send->Log($logdata);//记录机柜日志
                    $configures = $config['info'];
                    $this->assign('con',$configures);
                }*/

                $this->assign('v',$cabinet_id);
                return $this->fetch('../application/publicview/equipment/updateconf.html');
            }
        }
    }

    public function info(){

        if ( Request::instance()->isPost() ) {
            $cabinet_id = input('param.cabinet_id');//充电宝ID
            $lockid = input("param.lockid");//锁ID
            if(!empty($cabinet_id)){
                $Send = new Send($cabinet_id);
                $ret = $Send->EjectDevice($lockid);//弹出指定充电宝
                //var_dump($ret);die;
                if($ret['types']){
                    /*$logdata = array(
                        'oid' => session('oid'),
                        'mode' => 2,
                        'operation' => 1,
                        'info' => $lockid,
                        'resstatus' => $ret['types'],
                        'result' => $ret['info'],
                        'create_user'  => session('id'),
                      );
                      isset($ret['hex'])? $result['hex']=$ret['hex']:'';
                      $Send->Log($logdata);//记录机柜日志*/
                    $oid = session('oid');$m = 'ausagent'; $c = 'Equipment'; $action="info"; $uid=session('id'); $querystring = '弹出机柜'.$cabinet_id.'锁id'.$lockid;
                    $ip = get_ip();$os = get_os();
                    set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                    return ['code'=>0, 'msg'=>lang('弹出充电宝成功！')];
                }else{
                    return ['code'=>-1050, 'msg'=>lang('弹出充电宝失败！')];
                }
            }
        }else{
            $batteryid = input('param.batteryid');
            $key = input('param.key');
            $power = input('param.power');
            $cabinetid = input("param.cabinetid");
            $data  = array(
                'cabinetid' => $cabinetid,
                'key' => $key,
                'power' => $power,
                'batteryid' => $batteryid,

            );
            $this->assign("data",$data);
            return $this->fetch('../application/publicview/equipment/info.html');
        }

    }
    public function ota(){
        $pages = 20;
        $did = Request::instance()->get('did','','number_int');
        if(!empty($did)){
            //var_dump($did);die;
            $data['id'] = $did;
            $data['is_delete'] = 0;
            if(Db::name( 'charecabinet_version')->update($data)){
                //$this->redirect('index');
                return ['code'=>0, 'msg'=>lang('删除成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('删除失败！')];
            }
        }
        if ( Request::instance()->isPost() ) {
            $path = 'uploads/ota/';
            if($_FILES['file']['name']){

                $file = Request::instance()->file('file');
                //var_dump($file);
                $file_info = $file->move($path,'');
                $file_info = $file_info->getSaveName();
                $info = $file_info;
                $file_info = $path.$file_info;//var_dump($file_info);die;
                $data2['file'] = '/'.$file_info;

                Loader::import('ftp.ftp');
                $ftp = new \Ftp();
                //服务器地址(IP or domain)
                $data['server'] = config('ftp.addr');
                //ftp帐户
                $data['username'] = config('ftp.username');
                $data['password'] =config('ftp.password');
                $user = $data['username'];
                $pwd = $data['password'];
                //ftp密码

                //ftp端口,默认为21
                $data['port'] = config('ftp.port');
                //是否开启被动模式,true开启,默认不开启
                //var_dump($data['file']);die;
                //$con = $ftp->start($data);
                $remote = $info;
                $local = $_SERVER['DOCUMENT_ROOT'].'/uploads/ota/'.$info;
                $source = fopen("$local","r");
                $conn = ftp_connect($data['server'],$data['port'],30) or die("Could not connect");
                ftp_login($conn,"$user","$pwd");
                $result = ftp_put($conn,"$remote",$source,FTP_ASCII);
                var_dump($result);

            }
            //return ['code'=>-1050, 'msg'=>'上传失败'];
        }
        $version=Db::name('charecabinet_version')
            ->where('is_delete',1)
            ->order('create_time DESC')
            ->paginate($pages);
        $this->assign('list',$version);
        return $this->fetch('../application/publicview/equipment/ota.html');
    }

    public function otadd(){
        return $this->fetch('../application/publicview/equipment/otadd.html');
    }

    public function updatestatus(){
        if ( Request::instance()->isPost() ) {
            $filename = input('file_name');
            $cabinet_id = input('cabinet_id');
            $addr = config('ftp.addr');
            $port = config('ftp.port');
            $username = config('ftp.username');
            $password = config('ftp.password');
            $data = array(
                'filename' 		=>      $filename,
                'cabinet_id'  	=>		$cabinet_id,
                'addr'			=>		$addr,
                'port'			=>		$port,
                'username'		=>		$username,
                'password'		=>		$password,

            );
            var_dump($data);die;
        }else{
            $cabinet_id = input('param.cabinet_id');
            $version=Db::name('charecabinet_version')
                ->where('is_delete',1)
                ->select();
            $this->assign('list',$version);
            $this->assign('id',$cabinet_id);
            return $this->fetch('../application/publicview/equipment/updatestatus.html');
        }
    }

}